﻿var main_id;
var editor;
KindEditor.ready(function (K) {
    editor = K.create('#content1', {
        cssPath: './kindeditor/plugins/code/prettify.css',
        uploadJson: './kindeditor/upload_json.ashx',
        fileManagerJson: './kindeditor/file_manager_json.ashx',
        allowFileManager: true,
        afterCreate: function () {
            var self = this;
            self.sync();
        },
        //同步KindEditor值
        afterBlur: function () { this.sync(); }
    });
    prettyPrint();
  
});

KindEditor.ready(function (K) {
    var d = new Date();
    var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
    var classname = $("#img_class option:selected").text() == "选择分类" ? "选择分类" : $("#img_class option:selected").text();
    editor_Plugin = K.editor({
        uploadJson: './kindeditor/upload_json.ashx?Custom_directory=' + classname + '&t=' + t,
        fileManagerJson: './kindeditor/file_manager_json.ashx',
    });
    K('#J_selectImage').click(function () {
        editor_Plugin.loadPlugin('multiimage', function () {
            editor_Plugin.plugin.multiImageDialog({
                clickFn: function (urlList) {
                    var div = K('.gridly');
                    div.html('');
                    var count = $(".gridly").find("div").length;
                    K.each(urlList, function (i, data) {
                        div.append('<div class="brick small" id=' + Number(i + count) + ' style="position: absolute; left: 0px; top: 0px;"><img index=' + Number(i + count) + ' name="p' + Number(i + count) + '" width="120px" height="120px" src=' + data.url + ' ondblclick="show(this.name);" alt="" /><a class="delete" href="#">×</a></div>')
                    });
                    //生成json  arr[i].id排序索引  
                    editor_Plugin.hideDialog();
                    $('.gridly').gridly();
                    $.initPicJson.init("gridly");
                }
            });
        });
    });
});
function load() {
    KindEditor.ready(function (K) {
        var d = new Date();
        var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
        var classname = $("#img_class option:selected").text() == "选择分类" ? "选择分类" : $("#img_class option:selected").text();
        editor_Plugin = K.editor({
            uploadJson: './kindeditor/upload_json.ashx?Custom_directory=' + classname + '&t=' + t,
            fileManagerJson: './kindeditor/file_manager_json.ashx',
        });
    });
}


var index = 0, _name = null;
function show(name) {
    _name = name;
    index = layer.open({
        type: 1,
        title: false,
        area: ['300px', '188px'],
        closeBtn: 0,
        shadeClose: true,
        scrollbar: false,
        //skin: 'yourclass',
        content: '<div align="center"><textarea id="alttext" style="width:98%;height:160px;resize:none;background:transparent;border-style:none;">' + $("img[name='" + _name + "']").prop("alt") + '</textarea><input class="am-btn am-btn-primary am-btn-xs" type="button" value="确定" onclick="addalt();"/></div>'
    });
}
function addalt() {
    $("img[name='" + _name + "']").prop("alt", $("#alttext").val());
    $.setPicJson.create("gridly", _arr);
    layer.close(index);
}
//数据库操作
function addrow(table,fn,mold) {
    var json;
    var classid = uuid(6, 16);
    var imagelist = _v != null ? _v : v;
    console.log(imagelist);
    var title = $("#title").val();
    var classname = $("#classname option:selected").text();
    var content = editor.html();
    var d = new Date();
    var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
    var Flags = fn;
    var sqlstring = "insert into "+table+" values('" + classid + "','" + imagelist + "','" + classname + "','" + title + "','" + content + "','" + t + "','null');";
    console.log(sqlstring);
    return $.ajax({                                                  //调用jquery的ajax方法   
        type: "POST",                                      //设置ajax方法提交数据的形式   
        url: "handler/ExecuteHandler.ashx",                                       //把数据提交到ashx  
        data: {
                "type": "insert",
                "mold":mold,
                "classid":classid,
                "imagelist": imagelist,
                "title": title,
                "classname": classname,
                "content": content,
                "t": t,
                "Flags": Flags,
                "table": table
            },
       //输入框writer中的值作为提交的数据 
        dataType:JSON,
        beforeSend: function () {

        },
        success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
            //如果有必要，可以把msg变量的值显示到某个DIV元素中 
            layer.msg('处理成功', { icon: 1, time: 2000 });
            JsonData = {};
            return true;
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                layer.msg('处理成功', { icon: 1, time: 2000 });
                JsonData = {};
                return true;
            }
            layer.msg('处理失败', { icon: 2, time: 2000 });
            return false;
        },
    });
}

jQuery.Init = {
    load: function (id,url,control_id, table) {
        var sqlstring = "select * from " + table + " where id='" + id + "'";
        var tmp = Math.random().toString();
        $.ajax({
            type: 'POST',
            url: url + tmp,
            data: "sql=" + sqlstring,
            dataType: 'json',
            cache: false,
            beforeSend: function () {
                dialogID = layer.load(2, { shade: [0.1, '#fff'] });
            },
            success: function (data, textStatus) {
                layer.close(dialogID);
                var jsonData = eval(data);
                var div = $('.gridly');
                //div.html('');
                $.each(jsonData, function (index, objVal) { //遍历对象数组，index是数组的索引号，objVal是遍历的一个对象。objVal["属性"]可取到对应的属性值。 
                    $("#" + control_id[0]).prop("value", objVal["Title"]);
                    $("#" + control_id[1] + " option[text='" + objVal["classname"] + "']").attr("selected", true);
                    editor.text(objVal["Content"]);
                    if (objVal["ImageList"]) {
                        var parentJson = eval('(' + objVal["ImageList"] + ')');// 多维json 需要加（''）
                        $.each(parentJson, function (parent_index, parent_value) {
                            var childJson = eval(parent_value);
                            var num = 1;
                            var str = "";
                            $.each(childJson, function (child_indx, child_value) {
                                if (num == 1) {
                                    str = "<div class='brick small' id='" + child_value + "'style='position: absolute; left: 0px; top: 0px;'><img index='" + child_value + "' name='p" + child_value + "' width='120px' height='120px' ";
                                    num = num + 1;
                                }
                                else if (num == 2) { str = str + "src='" + child_value + "' ondblclick='show(this.name);' "; num = num + 1; }
                                else if (num == 3) { str = str + "alt='" + child_value + "' /><a class='delete' href='#'>×</a></div>"; num = 1; }
                            });
                            div.append(str);
                        });
                        $('.gridly').gridly();
                        $.initPicJson.init("gridly");
                    }
 
                });
            },
            error: function (xhr) {
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                    console.log(xhr);
                    this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                    return;
                }
                layer.close(dialogID);
                layer.msg('加载失败', { icon: 1, time: 2000 });
                return;
            },

        });
    }
}
jQuery.GetQueryString = {
    Get: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
}


function Pic_Insert(data) {
    var values = null;
    var jsonData = eval(data);
    $.each(jsonData, function (index, objVal) {
        var classname = $("#img_class option:selected").text() == "选择分类" ? "选择分类" : $("#img_class option:selected").text();
        if ($("#img_class option:selected").text() == "选择分类") {
            var regA = new RegExp("(?=\/image\/).*(?=\/*\/)");
            var strA = objVal.substr(1).match(regA);
            var classname = strA[0].substr(7);
            var regB = new RegExp(".*(?=\/image\/).*(?=\/*\/).?");
            var strB = objVal.substr(1).match(regB);
            var filename = objVal.substring(strB[0].length + 1);
        }
        else {
            var regB = new RegExp(".*(?=\/image\/).*(?=\/*\/).?");
            var strB = objVal.substr(1).match(regB);
            var filename = objVal.substring(strB[0].length + 1);
        }
        var classid = uuid(6, 16);
        var d = new Date();
        var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
        if (index == 0) {     
            values = "('" + classid + "','" + classname + "','" + filename + "','" + objVal + "','"+ t +"')";
        } else {

            values += ",('" + classid + "','" + classname + "','" + filename + "','" + objVal + "','" + t + "')";
        }
    });
    var sqlstring = "insert into gallery (id, classname , filename, path , time) values " + values;
    $.ajax({                                                  //调用jquery的ajax方法   
        type: "POST",                                      //设置ajax方法提交数据的形式   
        url: "handler/ExecuteHandler.ashx",                                       //把数据提交到ashx  
        data: "sql=" + sqlstring,     //输入框writer中的值作为提交的数据 
        beforeSend: function () {

        },
        success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
            //如果有必要，可以把msg变量的值显示到某个DIV元素中 
            //layer.msg('处理成功', { icon: 1, time: 2000 });
            JsonData = {};
            return true;
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return false;
            }
            //layer.msg('处理失败', { icon: 2, time: 2000 });
            return false;
        },
    });
}